package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author qzh
 * @create 2020-01-10 2020/1/10
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Override
    public void add(List<OrderSetting> list) {
        if(list!=null && list.size()>0){

            for (OrderSetting orderSetting : list) {
                //根据orderSetting的date查询数据库是否有一样的记录
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if(countByOrderDate>0){
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    orderSettingDao.add(orderSetting);
                }
            }


        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {

        String begin = date+"-1";
        String end = date + "-31";
        List<Map> result = new ArrayList<>();
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(begin,end);
        for (OrderSetting orderSetting : list) {
            Map map = new HashMap<String,Object>();
            map.put("date",orderSetting.getOrderDate().getDate());
            map.put("number",orderSetting.getNumber());
            map.put("reservations",orderSetting.getReservations());
            result.add(map);
        }
        return result;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //先查询当前日期是否进行了预约设置
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if(countByOrderDate>0){
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else{
            orderSettingDao.add(orderSetting);
        }


    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();

        Integer pageSize = queryPageBean.getPageSize();

        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page = orderSettingDao.findByCondition(queryString);
        List<Order> result = page.getResult();
        long total = page.getTotal();
        PageResult pageResult = new PageResult(total,result);
        return pageResult;
    }



    public Result addOrder(Member member, Integer[] checkitemIds) throws Exception {
        Integer setmealId=null;
        for (Integer checkitemId : checkitemIds) {
            setmealId = checkitemId;
        }
        String orderDate = member.getOrderDate();
        orderDate = orderDate.replace("Z", " UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date time = format.parse(orderDate);
            orderDate = defaultFormat.format(time);
        } catch (Exception e) {
            e.printStackTrace();
        }

        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting==null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约

        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations>=number){
            //预约人数已满
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.判断用户是否以及是会员
        String phoneNumber = member.getPhoneNumber();
        Member member1 = memberDao.findByTelephone(phoneNumber);//数据库中的member
        if(member1!=null){
            if (!member1.getName().equals(member.getName()) || !member1.getIdCard().equals(member.getIdCard())){
                //用户输入的基本信息和数据库中的不一致
                return new Result(false,"基本信息有误");
            }
            Integer id = member1.getId();
            Date order_Date = DateUtils.parseString2Date(orderDate);
            Order order = new Order(id, order_Date,setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list!=null&&list.size()>0){
                //重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //不是会员则自动完成注册并进行预约
            memberDao.add(member);//自动注册
        }
        //进行预约，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));

        order.setOrderType("线上");
        order.setOrderStatus(Order.ORDERSTATUS_NO);

        order.setSetmealId(setmealId);
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS,order);
    }

    @Override
    public Result editOrder(Member member, Integer[] checkitemIds) throws Exception {
        Integer setmealId=null;
        for (Integer checkitemId : checkitemIds) {
            setmealId = checkitemId;
        }
        String orderDate = member.getOrderDate();


        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting==null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约

        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations>=number){
            //预约人数已满
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.判断用户是否以及是会员
        String phoneNumber = member.getPhoneNumber();
        Member member1 = memberDao.findByTelephone(phoneNumber);//数据库中的member
        if(member1!=null){
            if (!member1.getName().equals(member.getName()) || !member1.getIdCard().equals(member.getIdCard())){
                //用户输入的基本信息和数据库中的不一致
                return new Result(false,"基本信息有误");
            }
            Integer id = member1.getId();
            Date order_Date = DateUtils.parseString2Date(orderDate);
            Order order = new Order(id, order_Date,setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list!=null&&list.size()>0){
                //重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //不是会员则自动完成注册并进行预约
            memberDao.add(member);//自动注册
        }
        //进行预约，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));

        order.setOrderType("线上");
        order.setOrderStatus(Order.ORDERSTATUS_NO);

        order.setSetmealId(setmealId);
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS,order);
    }





    @Override
    public List<Setmeal> findAll() {

        return orderSettingDao.findAll();
    }

    @Override
    public void addOrderSetting(OrderMessage map, Integer[] setmealIds) {

        orderSettingDao.addOrderSetting(map);
        //打断所有关系
        orderSettingDao.deleteOrderMessageAndSetmealRel(map.getId());
        //
        if(setmealIds!=null&&setmealIds.length>0){
            for (Integer setmealId : setmealIds) {
                orderSettingDao.saveOrderMessageAndSetmealRel(setmealId,map.getId());
            }
        }



    }
}
